/*
* jQuery Floatbox Plugin 1.0.8
* Copyright (c) 2008 Leonardo Rossetti (motw.leo@gmail.com)
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function($) {
	$.floatbox = function(options) {
		//support for jquery 1.0 request by christoph@breidert.net
		var getWidth = function() {
			var version = parseInt($.prototype.jquery.match(/\d/gim)[1]);
			var width;
			if (version > 1) {
				width = $(window).width();
			} else {
				width = document.body.scrollWidth ? document.body.scrollWidth: document.documentElement.scrollWidth;
			}
			//return width*0.8;
			return width - 620;
		};

		var getHeight = function() {
			var version = parseInt($.prototype.jquery.match(/\d/gim)[1]);
			var height;
			if (version > 1) {
				height = $(window).height();
			} else {
				height = document.body.scrollHeight ? document.body.scrollHeight: document.documentElement.scrollheight;
			}
			return height;
		};
		var getBgheight = function() {
			return ((is_IE && $.browser.version != "8.0") ? 
						($.browser.SafariMobile) ? 
							(($(document).height()>$(window).height()?$(document).height():$(window).height())+($("#searchhistory").is(":hidden")?247:0))
							: document.body.clientHeight
						: "100%"
					);
		};
		var is_IE = ($.browser.msie || $.browser.SafariMobile) ? true: false;
		//if($.browser.SafariMobile){alert("is this ipad?")}
		var settings = $.extend(true, {
			bg: "floatbox_bg",
			box: "floatbox_box",
			content: "",
			button: "<div><a role='button' href='javascript:void(0);' class='close-floatbox'>Close</a></div>",
			desc: "This is a popup box, press esc key to close.",
			fade: false,
			ajax: null,
			buttonPosition: "bellow",
			boxConfig: {
				position: (is_IE) ? "absolute": "fixed",
				zIndex: 9,
				//width: "620px",//getWidth() + "px",
				width: ((is_IE) ? document.body.clientWidth: "100%"),
				//width: getWidth() + "px",
				//marginLeft: "-" + (getWidth() / 2) + "px",
				//height: "auto",
				height: getBgheight(),
				//top: "20%",
				left: "0",
				backgroundColor: "#000",
				opacity: "0.80"
				//display: "none"
			}
		},
		options);

		//inserts floatbox and sets its content
		var loadDiv = function() {
			$("#" + settings.box).remove();
			var content = typeof settings.content === "string" ? settings.content: settings.content.clone();

			//inserts the floating box in the document
			$("<div></div>").attr({
				id: settings.box,
				role: "alertdialog"
			})
				.appendTo("body")
				.html(content)
				.css(settings.boxConfig)
				.css("margin-top", $("#" + settings.box).height() > getHeight() ? "0": "-" + $("#" + settings.box).height() / 2 + "px").css("top", "150px")
				.css("position", $("#" + settings.box).height() > getHeight() ? "absolute": (is_IE) ? "absolute": "fixed")
				.end();
			$("<div></div>").attr({
				id: "fjmybox"
			})
				.appendTo("body")
				.html(content)
				.css({
					position: (is_IE) ? "absolute": "fixed",
					zIndex: 10,
					left: (getWidth() / 2) + "px",
					background: "#fff"
				})
				.width(622)
				.height(324)
				.end();
			//checks if it needs to fade or not
			if (settings.fade) {
				$("div#" + settings.box).fadeIn(200);
			} else {
				$("#" + settings.box).show();
			}
		};
		var showBox = function() {
			//inserts the background element in the document
			loadDiv();
			//sets if ajax is needed(already detectets if it is POST or GET)
			if (settings.ajax) {
				$.ajax({
					type: settings.ajax.params === "" ? "GET": "POST",
					url: settings.ajax.url,
					data: settings.ajax.params,

					beforeSend: function() {
						$("#fjmybox").html(settings.button +"<div id=\"loading\"><img src=\"template//images/indicator.gif\"/>"+settings.ajax.before+"</div>").find(".close-floatbox").bind("click",
						function() {
							closeBox()
						});
					},

					success: function(data) {
						//$("body").append(settings.ajax.url);
						var resethtml = "";
						if(data.itemid==null||data.itemid==undefined||data.itemid==""){
                alert("API failed.");
                closeBox();
						}else{
                var resethtml = ShowItem(settings.ajax.sitename, data, settings.ajax.itemid);
                //$("#" + settings.box)
                $("#fjmybox").html(settings.button + resethtml).find(".close-floatbox").bind("click",
                function() {
                  closeBox()
                });
                //$("#itemimg").parent().css({"float":"left","text-align":"left","width":"100%"});
                $("#itemimg").attr("style", "").hide(); ($("#itemimg").parent()).width(280).height(187);
                checkimgload("#itemimg", 237, 180);
                //fiximagessize("#itemimg",237,180);
                checkprice(settings.ajax.sitename, data, settings.ajax.itemid);
						}
					},
					complete: function(XMLHttpRequest, textStatus) {
						if (settings.ajax.finish) {
							settings.ajax.finish;
							//settings.ajax.finish(XMLHttpRequest, textStatus);
						}
					},
					//contentType: "json",
					dataType: 'json'
				});
			}else{
          $("#fjmybox")
            .html(settings.content)
            //.css({width:"100px",height:"50px",left:(getWidth()+520 )/ 2 + "px",})
            .css({height:"50px",border: "3px solid #80BAEE","padding-top":"30px"})
            .end();
			}
		};
		var checkprice = function(site, items, sitemid) {
			var parentdiv = "#search_result";
			if (settings.ajax.regetprice == "no") {
				parentdiv = "#search_history";
			}
			var itembox = $(parentdiv + " #items_" + sitemid);
			var pricebox1 = itembox.find(".item_price");
			var itemprice = $.toNumber(pricebox1.text());
			if(itemprice==0){itemprice = $(".result_f #itemprice").text();}
			
			if ((itemprice == search_interface["_Str_Unknow"]) && site == "amazon") {
				amazon_price_url = items["url"];
				//window.open("/WebService/search.php?type=getprice&url="+amazon_price_url);
				////////////////////////////////////////////////////////////
				$.ajax({
					type: "GET",
					url: "./WebService/search.php?type=getprice&url=" + amazon_price_url,
					beforeSend: function() {
						$(".result_f #itemprice").html("<img src=\"/template/images/sloading.gif\" />");
						pricebox1.html("<img src=\"/template/images/sloading.gif\" />");
					},
					success: function(data) {
						$(".result_f #itemprice").text(data);
						pricebox1.text(data + search_interface["_yen"]);
						itembox.attr("data-sortprice", $.toSortNumber(data));
					}
				});
				////////////////////////////////////////////////////////////
			}else{
          $(".result_f #itemprice").text(itemprice);
			}
		};
		var ShowItem = function(site, items, sitemid) {
			var resulthtml = "<div class=\"result_f\"><div class=\"items\"><div class=\"item_sites item_site_##site#\"></div><div class=\"item_img\"> <p ><img src=\"##img#\" alt=\"##title#\" id=\"itemimg\" class=\"item_main_images\"/></p><p>##itembutton#</p><p>##itemgoto# ##itemwatch#</p></div><div class=\"item_info\"><h3>##title#</h3><div class=\"item_caption\"><ul>##info# </ul></div><div class=\"item_store\">##stone#</div></div></div></div>";
			stonename = items["store"];
			//price
			var itemprice = items["price"];
			if (itemprice == null || itemprice == "") {
				itemprice = search_interface["_Str_Unknow"];
			}else{
				itemprice=$.toNumber(itemprice);
			}
			//end price
			stonename = (stonename == null) ? "": stonename;
			//if (stonename.indexOf("gif") > 0) {
			if (/.*\.gif/i.test(stonename)) {
				stonename = "<img src='" + stonename + "'/>";
			} else if (1==stonename) {
        stonename = '<img src="/template/images/premium.gif" alt="">';
			} else if (stonename.length > 0) {
				stonename = '<img class="bg logos stone" src="/template/images/clear.gif" alt="">' + stonename
			} else if (stonename.length == 0 && settings.ajax.itemtype == "shopping") {
				stonename = '<img src="/template/images/premium.gif" alt="">';
				if (site != "rakuten") {
					stonename_null = $("#items_" + sitemid).find(".item_store").text();
					if (stonename_null != "" && stonename_null != null) {
						stonename = '<img class="bg logos stone" src="/template/images/clear.gif" alt="">' + stonename_null;
					}
				}
			}
			//itemdate = GetTime(items["endtime"]).replace("s","Second(s)").replace("d","Day(s)").replace("h","Hour(s)").replace("m","Minute(s)");
			itemdate = GetTime(items["endtime"]).replace("s", "##s#").replace("d", "##d#").replace("h", "##h#").replace("m", "##m#");
			itemdate = itemdate.replace("##s#", "Second(s)").replace("##d#", "Day(s)").replace("##h#", "Hour(s)").replace("##m#", "Minute(s)");

			//item_button
			if (settings.ajax.itemtype == "shopping") {
				buy_img = "ShopAddList.gif";
			} else {
				buy_img = "bigicon.gif";
			}
			item_button = "";
			item_towatch = "";
			item_button_goto = "<a href=\"" + items["url"] + "\"  target=\"_blank\" ><img src=\"/template/images/" + search_lang + "/goDataSite.gif\" /></a>";
			if (site == "yahoo" && settings.ajax.itemtype == "auction") {
				item_button = "<a href=\"" + $.format(url_yahoo_auction, search_lang, items["itemid"]) + "\" target=\"_blank\"><img src=\"/template/images/" + search_lang + "/" + buy_img + " \" /></a>";
				item_button += "<a href=\"" + $.format(url_yahoo_sniper, search_lang, items["itemid"]) + "\" target=\"_blank\"><img src=\"/template/images/" + search_lang + "/Sniperbid.gif\" /></a>";
				item_towatch = "<a href=\"" + $.format(url_watchlist, search_lang, items["itemid"]) + "\" target=\"_blank\"><img src=\"/template/images/" + search_lang + "/BidAddList.gif\" /></a>";
			} else {
				if (site == "yahoo") {
					siteflag = 1;
				} else if (site == "rakuten") {
					siteflag = 2;
				} else if (site == "amazon") {
					siteflag = 3;
				} else if (site == "bidders") {
					siteflag = 4;
				} else if (site == "kakaku") {
					siteflag = 5;
				} else if (site == "calamel") {
					siteflag = 7;
				}else{
					siteflag = 6;
				}
				item_button = "<a href=\"" + $.format(url_shopping, search_lang, items["itemid"], siteflag) + "\" target=\"_blank\"><img src=\"/template/images/" + search_lang + "/" + buy_img + "\" /></a>";
			}
			item_button += "<a href=\"" + $.format(url_calculator, search_lang, "##price#") + "\" target=\"_blank\"><img src=\"/template/images/" + search_lang + "/countPay.gif\" /></a>";
			if (settings.ajax.itemtype == "auction") {
				content_html_title = search_interface["_auction"];
				content_html_price = search_interface["_item_price"];
			} else {
				content_html_title = search_interface["_shopping_title"];
				content_html_price = search_interface["_item_shopprice"];
			}
			var content_html = "<li>●<strong>" + content_html_title + "&nbsp;ID&nbsp;:&nbsp;</strong>" + items["itemid"] + "</li>";
			content_html += "<li>●<strong>" + content_html_price + "&nbsp;:&nbsp;</strong><span id=\"itemprice\">##price#</span>" + search_interface["_yen"] + "</li>";

			if (settings.ajax.itemtype == "auction") {
				var buynowprice = items["bidorbuy"];
				var item_bids = items["bids"];
				if (buynowprice == "" || buynowprice == null) {
					buynowprice = search_interface["_Str_Noprice"];
				} else {
					buynowprice += search_interface["_yen"]
				}
				if (item_bids == "" || item_bids == null) {
					item_bids = "0";
				}
				var item_condition = items["condition"];
				if (item_condition == "" || item_condition == null) {
					item_condition = search_interface["_Str_Unknow"];
				} else if (item_condition == "new") {
					item_condition = search_interface["_Str_Newitem"];
				} else {
					item_condition = search_interface["_Str_Olditem"];
				}
				content_html += "<li>●<strong>" + search_interface["_item_buynow"] + "&nbsp;:&nbsp;</strong>" + buynowprice + "</li>";
				content_html += "<li>●<strong>" + search_interface["_item_bids"] + "&nbsp;:&nbsp;</strong>" + item_bids + "</li>";
				content_html += "<li>●<strong>" + search_interface["_item_lefttime"] + "&nbsp;:&nbsp;</strong>" + itemdate + "</li>";
				content_html += "<li>●<strong>" + search_interface["_item_state"] + "&nbsp;:&nbsp;</strong>" + item_condition + "</li>";
				if (items["store"] == "" || items["store"] == null) {
					if (site == "yahoo") {
						content_html += "<li>●<strong>" + search_interface["_item_type"] + "&nbsp;:&nbsp;</strong>" + search_interface["_item_seller"] + "</li>";
					} else { //bidders
						content_html += "<li>●<strong>" + search_interface["_item_type"] + "&nbsp;:&nbsp;</strong>" + search_interface["_Str_Unknow"] + "</li>";
					}
				} else {
					content_html += "<li>●<strong>" + search_interface["_item_type"] + "&nbsp;:&nbsp;</strong>" + search_interface["_item_store"] + "</li>";
				}
			}
			//送料
			content_html += "<li>●<strong>" + search_interface["_item_post"] + "&nbsp;:&nbsp;</strong>";
			if (items["postageFlag"] == 0 || items["postageFlag"] == "送料無料") {
				content_html += search_interface["_item_post_s2"];
			} else {
				content_html += search_interface["_item_post_s1"];
			}
			content_html += "</li>";
			//税
			content_html += "<li>●<strong>" + search_interface["_item_taxFlag"] + "&nbsp;:&nbsp;</strong>";
			if (items["taxFlag"] == 0) {
				content_html += search_interface["_item_taxFlag_1"];
			} else {
				content_html += search_interface["_item_taxFlag_2"];
			}
			content_html += "</li>";
			//content_info.html(url);
			iteminfo = content_html;

			addhtml = resulthtml.replace(/##site#/g, site);
			addhtml = addhtml.replace(/##itemid#/g, items["itemid"]);
			addhtml = addhtml.replace(/##title#/g, items["title"]);

			addhtml = addhtml.replace(/##itembutton#/g, item_button);
			addhtml = addhtml.replace(/##itemgoto#/g, item_button_goto);
			addhtml = addhtml.replace(/##itemwatch#/g, item_towatch);
			//if(items["img"]==""){items["img"]="/template/images/no_image.gif"}
			if (items["img"] == "") {
				items["img"] = $("#items_" + sitemid).find("img").attr("src")
			}
			//items["img"]=$("#"+sitemid).find("img").attr("src");
			addhtml = addhtml.replace(/##img#/g, items["img"]);

			addhtml = addhtml.replace(/##info#/g, iteminfo);

			addhtml = addhtml.replace(/##price#/g, itemprice);
			addhtml = addhtml.replace(/##stone#/g, stonename);
			return addhtml;
		}
		//hides floatingbox and background
		var closeBox = function() {
			if (settings.fade) {
				$("#" + settings.box).fadeOut(200,
				function() {
					$("#" + settings.box).remove();
					$("#fjmybox").remove();
				});
			} else {
				//for opera issues hide first and a timeout is needed to remove the elements
				$("#" + settings.box).hide();
				$("#" + settings.box).remove();
				$("#fjmybox").remove();
			}
		};
		//inits the floatbox
		var init = function() {
			//shows box
			showBox();
			//adds cross browser event to esc key to hide floating box
			$(document).one("keypress",
			function(e) {
				var escKey = $.browser.mozilla ? 0 : 27;
				if (e.which === escKey) {
					closeBox();
				}
			}).one("keydown",
			function(e) {
				var escKey = $.browser.mozilla ? 0 : 27;
				if (e.which === escKey) {
					closeBox();
				}
			});
			if (is_IE) {
				fixtopscroll();
				$(window).bind("scroll",
				function() {
					fixtopscroll();
				});
			} else {
				var topscroll = $(window).height() / 2;
				//alert(document.documentElement.scrollTop+"\n"+document.body.scrollTop);
				$("#fjmybox").css("top", topscroll - $(window).height() / 4);
				$("#" + settings.box).css("top", topscroll);
			}
		};
		var fixtopscroll = function() {
			var topscroll, myboxtopscroll;
			topscroll = document.documentElement.scrollTop + ($(window).height() / 2);
			myboxtopscroll = topscroll - $(window).height() / 4;
			if ($.browser.SafariMobile) {
				myboxtopscroll += $(window).scrollTop();
				$("body").css({height:"1670px"});
				$("#" + settings.box).css({
					"height": getBgheight()
				});
			};

			$("#fjmybox").css("top", myboxtopscroll);
			if ($.browser.version == "8.0" || $.browser.version == "9.0") {
				$("#" + settings.box).css({
					"top": topscroll
				});
			} else {
				$("#" + settings.box).css({
					"top": topscroll - $(window).height() / 2
				});
			}
		};
		//starts the plugin
		init();
	};
})(jQuery);